<script setup lang="ts">
import { reactive, ref, onMounted, getCurrentInstance } from 'vue'
// 组件
import { ElMessage } from 'element-plus'
// 接口
import type {
  IUserQueryData,
  IUserData,
  IUserListResponseData,
} from '@/api/system/user/type'
// api
import { reqUserList } from '@/api/system/user/index'

// 组件通信
const emitter =
  getCurrentInstance()?.appContext.config.globalProperties.$emitter
// 列表请求参数
let params = reactive<IUserQueryData>({
  username: '',
  name: '',
  page: 1,
  limit: 10,
})
// 列表数据
let tableData = ref<IUserData[]>([])
// 总条数
let total = ref<number>(0)
// 记录用户id
let oldUserId = ref<number>(0)
// 获取列表数据
const getList = async () => {
  const { data, code, message }: IUserListResponseData =
    await reqUserList(params)
  const { total: listTotal, records } = data
  if (code === 200) {
    tableData.value = records || []
    total.value = listTotal || 0
  } else {
    ElMessage({
      type: 'error',
      message,
    })
  }
}
// 分页切换
const handlePageChange = (currentPage: number, pageSize: number) => {
  params.page = currentPage
  params.limit = pageSize
  getList()
}
// 搜索
const handleQuery = () => {
  getList()
}
// 重置筛选条件
const handleReset = () => {
  params.username = ''
  params.name = ''
  params.page = 1
  getList()
}
// 列表多选
const handleRowClick = (row: IUserData) => {
  // 事件通信
  if (row.id === oldUserId.value) return
  oldUserId.value = row.id
  emitter.emit('divide_user_row_click', row)
}

onMounted(() => {
  getList()
})
</script>
<template>
  <el-container>
    <!-- 筛选条件 -->
    <el-header>
      <el-form :model="params" inline>
        <el-form-item label="用户名">
          <el-input v-model="params.username" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="params.name" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button type="primary" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-header>
    <!-- 表格 -->
    <el-main>
      <el-table :data="tableData" @row-click="handleRowClick" border>
        <el-table-column prop="username" label="用户名" align="center" />
        <el-table-column prop="name" label="姓名" align="center" />
      </el-table>
    </el-main>
    <!-- 分页 -->
    <el-footer>
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :current-change="params.page"
        :page-size="params.limit"
        @change="handlePageChange"
      />
    </el-footer>
  </el-container>
</template>
